package com.etoonet.android.demo.androidupdater

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import com.etoonet.android.updater.Updater
import com.etoonet.android.updater.UpdaterConfig
import javax.xml.datatype.DatatypeConstants.SECONDS
import android.app.DownloadManager
import android.util.Log
import com.etoonet.android.updater.DownloadInfo
import com.etoonet.android.updater.Updater.getLocalDownloadId
import io.reactivex.schedulers.Schedulers
import javax.xml.datatype.DatatypeConstants.SECONDS
import com.etoonet.android.updater.Updater.getLocalDownloadId
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.ObservableOnSubscribe
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.observers.DisposableObserver
import org.reactivestreams.Subscriber
import org.reactivestreams.Subscription
import java.util.concurrent.TimeUnit


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Updater.get().onInstallApkListener = object : Updater.UpdaterListener {
            override fun onInstallApk() {
                Toast.makeText(this@MainActivity, "开始安装", Toast.LENGTH_LONG).show()
            }
        }

        val config = UpdaterConfig.defaultConfig(this@MainActivity)
        config.fileUrl = "http://shouji.360tpcdn.com/iN1xk3hxyzVha56S4ik32G-qMmyz3Y0NcqHpRd6vUHYWU2IH3SZ_g0ztWJpKUpMt1bhXwxf9f3TAckjBdJvMwQ2.apk?sign=bd8d519d7530c221"
        val downloadId = Updater.get().download(config)

        // TODO 查询进度

        queryProgress(downloadId)
    }

    fun queryProgress(downloadId: Long) {
        val context = this@MainActivity
        Observable.interval(1, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<Long>() {

                    override fun onStart() {
                        super.onStart()

                        Log.e("TEST", "onStart")
                    }

                    override fun onComplete() {
                        Log.e("TEST", "下载完成")
                    }

                    override fun onNext(t: Long) {
                        val status = Updater.getDownloadStatus(context, downloadId)

                        val downloadInfo = Updater.getDownloadInfo(context, downloadId)

                        Log.e("TEST", "onNext, info: $downloadInfo")

                        Log.e("TEST", "onNext, status: $status")

                        when (status) {
                            DownloadManager.STATUS_SUCCESSFUL -> { // 成功
                                onComplete()
                                dispose()
                            }

                            DownloadManager.STATUS_RUNNING -> {
                                Log.e("TEST", "正在下载...")
                            }

                            DownloadManager.STATUS_PENDING -> { //
                                Log.e("TEST", "正在准备下载")
                            }

                            DownloadManager.STATUS_PAUSED -> {
                                Log.e("TEST", "下载暂停")
                            }

                            DownloadManager.STATUS_FAILED, -1 -> { // 失败
                                onError(Throwable("download is failed."))
                                dispose()
                            }
                        } // 其他情况暂不处理
                    }

                    override fun onError(e: Throwable) {
                        Log.e("TEST", "下载失败")
                    }
                })
    }

    class Test: ObservableOnSubscribe<DownloadInfo> {

        override fun subscribe(emitter: ObservableEmitter<DownloadInfo>) {

        }

    }

}
